#pragma once
#include "esepp.h"
#include "Session.h"

namespace ese
{
	class database
	{
	public:

		database() = delete;
		database( const database& ) = delete;
		database(database&&) = delete;
		database(session& ses) : m_jdb(JET_dbidNil)
			, m_session(ses)
			, m_last_error(JET_errSuccess) {}
		~database() { try { close(); } catch (...){} }

		const JET_DBID id(void) const { return m_jdb; }
		const JET_ERR last_error(void) const { return m_last_error; }
		session& session() const { return m_session; }

		bool close();
		bool open(std::string filePath, JET_GRBIT grbits = 0);
		bool create(std::string filePath, JET_GRBIT grbits = 0);

	private:
		ese::session& m_session;
		JET_DBID m_jdb;
		JET_ERR m_last_error;

	};

	inline bool database::close()
	{
		if (JET_dbidNil == m_jdb)
		{
			return true;
		}// if

		char path[MAX_PATH];

		if (JET_errSuccess != (m_last_error = ::JetGetDatabaseInfoA(m_session.id(), m_jdb, path, MAX_PATH, JET_DbInfoFilename)))
		{
			return false;
		}// if

		if (JET_errSuccess != (m_last_error = ::JetCloseDatabase(m_session.id(), m_jdb, 0)))
		{
			return false;
		}// if

		m_last_error = ::JetDetachDatabaseA(m_session.id(), path);
		m_jdb = JET_dbidNil;
		return (m_last_error == JET_errSuccess);
	}

	inline bool database::open(std::string filePath, JET_GRBIT grbits)
	{
		m_last_error = JetAttachDatabaseA(m_session.id(), filePath.c_str(), grbits);

		if ((m_last_error != JET_errSuccess) && (m_last_error != JET_wrnDatabaseAttached))
		{
			return false;
		}// if

		if (JET_errSuccess != (m_last_error = JetOpenDatabaseA(m_session.id(), filePath.c_str(), nullptr, &m_jdb, grbits)))
		{
			return false;
		}// if

		return true;
	}

	inline bool database::create(std::string filePath, JET_GRBIT grbits)
	{
		m_last_error = ::JetCreateDatabaseA(m_session.id(), filePath.c_str(), nullptr, &m_jdb, grbits);
		return ((m_last_error == JET_errSuccess)
			|| (m_last_error == JET_wrnDatabaseAttached)
			|| (m_last_error == JET_wrnFileOpenReadOnly));
	}

} // namespace